﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text; 
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.Invoice;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// Invoice opening by trade NOC ommand handler.
    /// </summary>
    public sealed class InvoiceOpeningByTradeNOCommandHandler : BaseCommandHandler, IRequestHandler<InvoiceOpeningByTradeNOCommand, bool>
    {
        private readonly IOrderBaseRepository _orderBaseRepository;
        private readonly IErrorLogRepository _errorLogRepository;
        public InvoiceOpeningByTradeNOCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOrderBaseRepository orderBaseRepository, IOptionsSnapshot<CasamielSettings> casamielSettings
            , IErrorLogRepository errorLogRepository) : base(netICService, httpClientFactory, casamielSettings)
        {
            _orderBaseRepository = orderBaseRepository;
            _errorLogRepository = errorLogRepository;
        }

        public async Task<bool> Handle(InvoiceOpeningByTradeNOCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            string appToken = "bd481f06d2e19accab48965ada3b8f14d66d02b78b345d67908e4dc8f9d8860aefe0ad391d8963586632c4cba89bf64a";
            var ordernetity = await _orderBaseRepository.GetByIcTradeNOAsync<ICasaMielSession>(request.TradeNO).ConfigureAwait(false);
            if (ordernetity != null && ordernetity.IsOpenInvoice.HasValue)
            {
                if (ordernetity.IsOpenInvoice == 1)
                {
                    var data = new { appToken, qrCode = ordernetity.InvoiceUrl };
                    var result = await PostAsync<ICResult>("api/NuoNuoAPI/ElectronicInvoiceAPI/GetOrderInvoiceInformationByQRCode", JsonConvert.SerializeObject(data), "InvoiceApi").ConfigureAwait(false);
                    if (result.code == 0)
                    {
                        
                        var info = JsonConvert.DeserializeObject<OrderInvoiceInformationRsp>(result.content);

                        if (info == null)
                        {
                            return false;
                        }
                        if (info.OrderInvoice == null)
                        {
                            return false;
                        }
                        var openreq = new
                        {
                            appToken,
                            orderno = info.OrderInvoice.OrderNO,
                            taxtType = ordernetity.InvoiceType == 1 ? 0 : 1,
                            buyername = ordernetity.InvoiceTitle,
                            taxnum = ordernetity.TaxpayerId,
                            phone = ordernetity.ContactPhone,
                            email = ordernetity.InvoiceEMail,
                            address = ordernetity.InvoiceAddress,
                            account = ordernetity.InvoiceOpeningBank,
                            tsfs = 2,
                        };

                        var resul1t = await PostAsync<ICResult>("api/NuoNuoAPI/ElectronicInvoiceAPI/InvoiceInformationbyOrderNo", JsonConvert.SerializeObject(openreq), "InvoiceApi").ConfigureAwait(false);
                        if (resul1t.code != 0) {
                            BizInfologger.Error(JsonConvert.SerializeObject(resul1t));
                            var errorlog = new ErrorLog
                            {
                                Loginfo =$"订单号{ordernetity.OrderCode},开票出错，{resul1t.msg}",
                                OPTime =DateTime.Now,
                                Type =2
                            };
                            await _errorLogRepository.SaveAsync<ICasaMielSession>(errorlog).ConfigureAwait(false);
                            return false;
                        }
                        //根据订单号开票
                        var req = new
                        {
                            appToken,
                            orderno = info.OrderInvoice.OrderNO,
                        };
                        var resul1t2 = await PostAsync<ICResult>("api/NuoNuoAPI/ElectronicInvoiceAPI/TicketOpeningbyOrderNo", JsonConvert.SerializeObject(req), "InvoiceApi").ConfigureAwait(false);
                        if (resul1t2.code == 0)
                        {
                            ordernetity.IsOpenInvoice = 2;

                            await _orderBaseRepository.UpdateAsync<ICasaMielSession>(ordernetity).ConfigureAwait(false);
                            BizInfologger.Trace($"开票{ordernetity.OrderCode},已开票");
                        }
                        else
                        {
                            var errorlog = new ErrorLog
                            {
                                Loginfo = $"订单号{ordernetity.OrderCode},开票出错，{resul1t2.msg}",
                                OPTime = DateTime.Now,
                                Type = 2
                            };
                            await _errorLogRepository.SaveAsync<ICasaMielSession>(errorlog).ConfigureAwait(false);
                        }
                         
                    }
                    return true;
                }
            }
            return true;
        }
    }
}